package org.springblade.modules.restaurant.controller;

import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springblade.core.mp.base.BaseEntity;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.secure.BladeUser;
import org.springblade.core.secure.utils.SecureUtil;
import org.springblade.core.tool.api.R;
import org.springblade.modules.restaurant.entity.Task;
import org.springblade.modules.restaurant.enums.StatusEnums;
import org.springblade.modules.restaurant.service.ITaskService;
import org.springblade.modules.restaurant.vo.TaskVO;
import org.springblade.modules.restaurant.wrapper.TaskWrapper;
import org.springdoc.core.annotations.ParameterObject;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author harry
 * @公众号 Harry技术
 */
@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("/api/restaurant/task")
@Tag(name = "任务表", description = "任务表接口")
public class ApiTaskController {

	private ITaskService taskService;

	@GetMapping("/page")
	@ApiOperationSupport(order = 3)
	@Operation(summary = "分页", description = "传入task")
	public R<IPage<TaskVO>> page(@ParameterObject Task task, @ParameterObject Query query) {

		BladeUser user = SecureUtil.getUser();
		if (user == null) {
			return R.fail("请求异常，请重新登录");
		}
		// 获取当前登录用户ID
		Long userId = user.getUserId();
		String role = user.getRoleName();
		String tenantId = user.getTenantId();
		log.info("当前登录用户ID:{},role:{},tenantId:{}", userId, role, tenantId);

		LambdaQueryWrapper<Task> wrapper = Wrappers.<Task>lambdaQuery()
			.eq(BaseEntity::getStatus, StatusEnums.ENABLE.getStatus())
			.like(StrUtil.isNotBlank(task.getTaskName()), Task::getTaskName, task.getTaskName())
			.eq(StrUtil.isNotBlank(task.getAreaIds()), Task::getAreaIds, task.getAreaIds())
			.eq(ObjUtil.isNotNull(task.getCycle()), Task::getCycle, task.getCycle())
			.eq(Task::getUserIds, userId)
			.orderByDesc(Task::getUpdateTime);

		IPage<Task> pages = taskService.page(Condition.getPage(query), wrapper);
		return R.data(TaskWrapper.build().pageVO(pages));
	}

	@GetMapping("/detail")
	@ApiOperationSupport(order = 1)
	@Operation(summary = "详情", description = "传入task")
	public R<TaskVO> detail(Task task) {
		Task detail = taskService.getOne(Condition.getQueryWrapper(task));
		return R.data(TaskWrapper.build().entityVO(detail));
	}
}
